package com.rmi.spring.server;
import java.rmi.RemoteException;
import java.util.stream.Stream;

import org.springframework.beans.FatalBeanException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.remoting.rmi.RmiServiceExporter;
import org.springframework.util.StringValueResolver;

import com.rmi.anno.server.RemoteService;
import com.rmi.registry.zk.ZooKeeperServiceRegistry;
public class ServiceAnnotationListener implements ApplicationListener<ContextRefreshedEvent> , EmbeddedValueResolverAware {

    private StringValueResolver resolver;
    
	@Override
	public void setEmbeddedValueResolver(StringValueResolver resolver) {
		this.resolver = resolver;
	}

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		if (event.getApplicationContext().getParent() == null) {
			System.out.println("程序启动");
			ApplicationContext ac= event.getApplicationContext();
			Stream.of(ac.getBeanDefinitionNames()).forEach(beanName->{
				Object bean = ac.getBean(beanName);
				RemoteService service = AnnotationUtils.findAnnotation(bean.getClass(), RemoteService.class);
		        if (null != service) {
		                RmiServiceExporter rmiServiceExporter = new RmiServiceExporter();
		                rmiServiceExporter.setServiceInterface(service.serviceInterface());
		                rmiServiceExporter.setService(bean);
		                String rmiRegistPort=resolver.resolveStringValue("${rmi.port}");
		                if (!org.springframework.util.StringUtils.isEmpty(rmiRegistPort)) {
		                    rmiServiceExporter.setRegistryPort(Integer.parseInt(rmiRegistPort));
		                }
		                String serviceName = service.serviceInterface().getName();
		          
		                rmiServiceExporter.setServiceName(serviceName);
		                try {
		                    rmiServiceExporter.afterPropertiesSet();
		                } catch (RemoteException remoteException) {
		                    throw new FatalBeanException("Exception initializing RmiServiceExporter", remoteException);
		                }
		                ZooKeeperServiceRegistry registry =  ac.getBean(ZooKeeperServiceRegistry.class);
		                registry.register(serviceName, "rmi://127.0.0.1:"+rmiRegistPort+"/"+serviceName);
		                System.out.println("注册服务："+serviceName+",at "+"rmi://127.0.0.1:"+rmiRegistPort+"/"+serviceName);
		            }
			});
		}
	}
}